<script setup>
import { ref, reactive, watch, onMounted, onBeforeUnmount, computed, unref } from "vue"
import { ElDatePicker, ElInputNumber, ElSwitch } from "element-plus"
import * as echarts from "echarts"
import { useDebounceFn } from "@vueuse/core"
const PREFIX = '/tokens-count/api'
const { uri, keys, title = '' } = defineProps(['uri','keys','title']) // keys = {name:"",value:""}
const dt = new Date().getTime()
const DAYTIME = 86400000
const max = ref(10)
const timeRange = ref([dt - max.value * DAYTIME, dt])
const users = ref([])
const isDynamic = ref(false);
const loopTime = ref(2)
const loopCD = ref(2)
const echartBox = ref();
let myChart;
let th;
const md = reactive(new Map())
const series = computed(() => {
    const res = [];
    for (const k of md.keys()) {
        // console.log(users.value)
        // if (users.value.includes(k)) {
        res.push({ name: k, type: 'line', showSymbol: false, data: unref(md.get(k)) })
    }
    return res;
})

const init = async () => {
    md.clear();
    clear();
    const sd = new Date(timeRange.value[0])
    const st = sd.getTime();
    const et = new Date(timeRange.value[1]).getTime()
    const cd = (et - st) / max.value;
    // const t = Math.round(cd / max.value);
    for(let i = 0;i < max.value;i++){
        console.log(i,st,st + cd * (i + 1))
        await add(initData(sd, st + cd * (i + 1)), false);
    }
    // await Promise.all(Array.from(Array(max.value).keys()).map((i) => add(initData(sd, st + cd * (i + 1), i), false)))
    users.value = [...md.keys()]
    // md.keys.map(k => md.get(k).filter(d => !!d))
}
const initData = (st = timeRange.value[0], et = timeRange.value[1], i = -1) => {
    const sd = new Date(st);
    const ed = new Date(et);
    const sdt = sd.toLocaleDateString().split('/').map(s => s.padStart(2, '0')).join('-') + ' ' + sd.toLocaleTimeString()
    const edt = ed.toLocaleDateString().split('/').map(s => s.padStart(2, '0')).join('-') + ' ' + ed.toLocaleTimeString()
    return { start_time: sdt, end_time: edt, query_all: false, index: i }
}

const refresh = () => {
    const dt = new Date().getTime()
    timeRange.value = [dt - max.value * DAYTIME, dt]
    // init();
}

const clear = () => {
    myChart?.setOption({
        ...option,
        series: []
    }, true);
}

const add = async (data, isDel = true) => {
    try {
        const url = `${PREFIX}${uri}?start_time=${data.start_time}&end_time=${data.end_time}&query_all=${data.query_all}`
        const ops = { method: 'GET', headers: { 'Content-Type': 'application/json' } }
        const resp = await fetch(url, ops);
        const json = await resp.json();
        const td = json.data || [];
        for (const t of td) {
            const name = t[keys.name]
            const value = t[keys.value]
            const ct = new Date(data.end_time).getTime();
            const ta = [].concat(md.get(name) || []);
            const index = data.index;
            if (isDel && ta.length >= max.value) {
                ta.shift();
            }
            const od = { name: data.end_time, value: [ct, value] };
            if(index > -1){
                ta[index] = od;
            }
            else{
                ta.push(od)
            }
            md.set(name, ta);
        }
    } catch (error) {
        console.error('====>',error)
    }
}



const loop = () => {
    clearInterval(th);
    th = setInterval(() => {
        timeRange.value[1] = new Date(timeRange.value[1]).getTime() + loopTime.value * 1000
        add(initData())
    }, loopCD.value * 1000);
}

const option = {
    // title:{text:title},
    tooltip: {
        trigger: 'axis'
    },
    xAxis: {
        type: 'time',
        splitLine: {
            show: true
        }
    },
    yAxis: {
        type: 'value',
        // boundaryGap: [0, '100%'],
        splitLine: {
            show: true
        }
    },
    series: []
}

onMounted(() => {
    myChart = echarts.init(echartBox.value)
    myChart.setOption(option)
    //
    init();
    if (isDynamic.value) { loop(); }
})

onBeforeUnmount(() => clearInterval(th))

watch(timeRange, () => init())

watch(series, useDebounceFn((v) => {
    if (v && Array.isArray(v)) {
        myChart.setOption({ series: v, legend: { data: v.map(t => t.name) } })
    }
}))

watch(isDynamic, (v) => v ? loop() : clearInterval(th))

watch(max, () => init())

</script>

<template>
    <div class="w-full h-full">
        <div class="h-40 flex gap-20 box-border p-x-10% items-centerr">

            <div class="text-18 fw-bold flex items-center gap-4 ">
                <div class="i-charm:chart-line"></div>
                <span>{{ title }}</span>
            </div>
            <div class="w-480 flex items-center gap-8">
                <span>时间范围</span>
                <el-date-picker v-model="timeRange" type="datetimerange" staart-placeholder="开始时间"
                    end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" date-format="YYY/MM/DD ddd"
                    time-format="A hh:mm:ss" unlink-panels />
            </div>
            <div class="flex items-center gap-8">
                <span>是否动态更新</span>
                <el-switch v-model="isDynamic" />
                <!-- <ElInputNumber v-model=""></ElInputNumber> -->
            </div>


            <div class="flex items-center gap-8">
                <span>更新间隔(秒)</span>
                <ElInputNumber v-model="loopTime" :disabled="isDynamic" />
            </div>
            <div class="flex items-center gap-8">
                <span>更新频率(秒)</span>
                <ElInputNumber v-model="loopCD" :disabled="isDynamic" :min="1" />
            </div>
            <div class="flex-1"></div>
            <div v-if="!isDynamic" class="text-24 flex items-center c-#67C23A  ">
                <div @click="refresh" class="i-solar:refresh-circle-linear  cursor-pointer  op-70 hover-op-100" title="刷新"></div>
            </div>
        </div>
        <div class="h-[calc(100%-10rem)] w-full relative">
            <div ref="echartBox" class="w-full h-full"></div>
        </div>
    </div>
</template>